//
//  KYZXHeadlineVC.m
//  KuYouZiXun
//
//  Created by lanou on 15/8/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//
#define kURL @"http://appapi.gamersky.com/v1/articletopad"

#define kSlideadUrl @"http://appapi.gamersky.com/v1/slidead"

#import "KYZXHeadlineVC.h"

#import "LJRequestManagerBlock.h"

#import "KYZXContentListModel.h"

#import "KYZXTableViewCell.h"

#import "KYZXWebVC.h"

#import "KYZXNewsVC.h"

#import "LJScrollView.h"

#import "KYZXScreen.h"

#import "UIImageView+WebCache.h"

#import "MJRefresh.h"

typedef NS_ENUM(NSInteger, RefreshType) {
    RefreshNew,
    RefreshMore,
    RefreshError//没有网的时候
};
@interface KYZXHeadlineVC ()<LJScrollViewDelegate>
{
    RefreshType _refreshType;
}
@property (strong, nonatomic)NSMutableDictionary *parameterDic;//参数字典

@property (strong, nonatomic)NSMutableArray *dataSource;//数据源

@property (strong, nonatomic)NSMutableArray *slideadData;//轮播图数据

@property (strong, nonatomic)NSDictionary *slideadDic;
@end

@implementation KYZXHeadlineVC


- (void)addRefreshNew
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _refreshType = RefreshNew;
        [self.parameterDic setValue:@"1" forKey:@"pageIndex"];
        [self requestData:self.parameterDic];
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}

- (void)addRefreshMore
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _refreshType = RefreshMore;
        NSString *page = [self.parameterDic valueForKey:@"pageIndex"];
        NSInteger pageNew = [page integerValue] + 1;
        
        [self.parameterDic setValue:[NSString stringWithFormat:@"%d",pageNew] forKey:@"pageIndex"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.parameterDic];
        [self requestData:dic];
    }];
}

- (void)endRefreshing{
    
    if (_refreshType == RefreshNew) {
        [self.tableView.header endRefreshing];
        [self addRefreshMore];
    }
    if (_refreshType == RefreshMore) {
        [self.tableView.footer endRefreshing];
    }
    
}


#pragma mark 懒加载属性

- (NSMutableArray *)dataSource{
    
    if(_dataSource == nil){
        _dataSource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataSource;
}


- (NSMutableArray *)slideadData{

    if (_slideadData == nil) {
        _slideadData = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _slideadData;
}

- (NSDictionary *)slideadDic{

    if (_slideadDic == nil) {
        _slideadDic = @{@"platformType":@1,@"appname":@"gsapp",@"appversion":@"1.4.4",@"deviceId":@"BC82D164-DDD7-4D08-B125-E670BE0E38E4"};
    }
    return _slideadDic;
}

- (NSDictionary *)parameterDic{
    
    if (_parameterDic == nil) {
        _parameterDic = [@{@"platformType":@1,@"appname":@"gsapp",@"appversion":@"1.4.4",@"deviceId":@"BC82D164-DDD7-4D08-B125-E670BE0E38E4",@"pageIndex":@"1",@"pageCount":@"20"} mutableCopy];
    }
    return _parameterDic;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self addRefreshNew];
    [self requestSlideadData:self.slideadDic];
    [self.tableView registerNib:[UINib nibWithNibName:@"KYZXTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.navigationController.navigationBarHidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


#pragma mark 获取数据

//请求数据
- (void)requestData:(NSDictionary *)parameterDic{
    
    [LJRequestManagerBlock manager:POST requestWith:kURL dic:parameterDic finish:^(NSData *data) {
        [self parseData:data];
    } error:^(NSError *error) {
        NSLog(@"数据获取错误 %@",error);
    }];
}


- (void)requestSlideadData:(NSDictionary *)dic{

    [LJRequestManagerBlock manager:POST requestWith:kSlideadUrl dic:dic finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *resultArray = dict[@"result"];
        for (NSDictionary *dic in resultArray) {
            KYZXContentListModel *model = [[KYZXContentListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.slideadData addObject:model];
        }
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"数据获取错误 %@",error);
    }];
}

//解析数据
- (void)parseData:(NSData *)data
{
    //程序第一次尽量的时候没有网,数据库里面也没有数据 所以会蹦,我们判断一下如果data为nil 直接返回
    if (data == nil) {
        //        NSLog(@"即没有网 数据库也没有数据");
        [self endRefreshing];
        return;
    }
    if (_refreshType == RefreshNew) {
        self.dataSource = nil;
    }
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSArray *resultArray = dict[@"result"];
    for (NSDictionary *dic in resultArray) {
        KYZXContentListModel *model = [[KYZXContentListModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.dataSource addObject:model];
    }
    [self endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KYZXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    KYZXContentListModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return 90;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KYZXContentListModel *model = _dataSource[indexPath.row];
    KYZXWebVC *webVC = [[KYZXWebVC alloc] init];
    webVC.generalId = model.generalId;
    [_newsVC.navigationController pushViewController:webVC animated:YES];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if ([_slideadData count] != 0) {
        NSMutableArray *viewArray = [[NSMutableArray alloc] initWithCapacity:0];
        for (int i = 0 ; i < [_slideadData count]; i++) {
            KYZXContentListModel *model = _slideadData[i];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150.0 / 320.0 * SCREEN_WIDTH)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.thumbnailUrl] placeholderImage:[UIImage imageNamed:@"_backimage"]];
            [viewArray addObject:imageView];
        }
        LJScrollView *scrollView = [[LJScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150.0 / 320.0 * SCREEN_WIDTH) viewArray:viewArray Animation:5];
        scrollView.delegate = self;
        return scrollView;
    }
    return nil;
 
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 150.0 / 320.0 * SCREEN_WIDTH;
}

//去除plain格式下tableview的区头粘性
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 150.0 / 320.0 * SCREEN_WIDTH; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}


- (void)scrollViewDidEndSelected:(LJScrollView *)scrollView viewArray:(NSArray *)viewArray atIndex:(NSUInteger)index{

    KYZXContentListModel *model = _slideadData[index];
    KYZXWebVC *webVC = [[KYZXWebVC alloc] init];
    webVC.generalId = model.generalId;
    [_newsVC.navigationController pushViewController:webVC animated:YES];
}

@end
